<template>
  <div>
    <el-dialog :visible="addVisible" title="新增受试者" width="700px" @close="handleCancel()">
      <!-- 表单 -->
      <el-form ref="formRef" label-width="200px" :model="formData" :rules="formRules" size="mini">
        <div v-for="(fItem, fIndex) in originTableHeadData" :key="fIndex">
          <div v-if="fItem.operation === '0' || (fItem.operation === '' && !fItem.variableType && fItem.variableName)">
            <el-form-item
              :label="`${fItem.variableName}${fItem.entry ? '(' + fItem.entry + ')' : ''}：`"
              v-if="fItem.variableType === '10' || specialField.includes(fItem.variable)"
              :prop="fItem.required === '0' || fItem.regEx ? fItem.variable : ''"
            >
              <!-- 单选 radio -->
              <el-radio-group
                style="width: 80%"
                v-if="
                  fItem.variableValue &&
                    fItem.variableValue.codeArrangement &&
                    fItem.variableValue.codeArrangement !== 3 &&
                    !specialField.includes(fItem.variable)
                "
                v-model="formData[fItem.variable]"
                @change="value => handleRadioChange(value, fItem)"
              >
                <el-row :span="24">
                  <el-col
                    :span="fItem.variableValue && fItem.variableValue.number ? 24 / fItem.variableValue.number : 6"
                    v-for="item in fItem.classify"
                    :key="item.codeValue"
                  >
                    <el-radio :disabled="fItem.readOnly === '0'" :label="item.codeValue" :key="item.codeValue">
                      {{ item.codeDescribe }}
                    </el-radio>
                  </el-col>
                </el-row>
              </el-radio-group>
              <!-- 选择框 -->
              <div v-else-if="!specialField.includes(fItem.variable)">
                <el-select
                  v-model="formData[fItem.variable]"
                  style="width: 80%"
                  :disabled="fItem.readOnly === '0'"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in fItem.classify"
                    :key="item.codeValue"
                    :label="item.codeDescribe"
                    :value="item.codeValue"
                  >
                  </el-option>
                </el-select>
              </div>
              <!-- 中心名称 -->
              <div v-else-if="fItem.variable === 'SITENAME'">
                <el-select
                  size="mini"
                  :disabled="fItem.readOnly === '0'"
                  style="width: 80%"
                  v-model="formData.SITENAME"
                  @change="handleCoreNameChange"
                >
                  <el-option
                    v-for="item in coreNameOptions"
                    :key="item.coreId"
                    :label="item.coreName"
                    :value="item.coreId"
                  ></el-option>
                </el-select>
              </div>
              <!-- 受试者状态 -->
              <div v-else-if="fItem.variable === 'STATUS'">
                <el-radio-group :disabled="fItem.readOnly === '0'" style="width: 80%" v-model="formData.STATUS">
                  <el-radio :label="item.codeValue" v-for="item in subjectStateOptions" :key="item.codeValue">{{
                    item.statusName
                  }}</el-radio>
                </el-radio-group>
              </div>
              <!-- eCRF状态 -->
              <div v-else-if="fItem.variable === 'CRFSTS'">
                <el-radio-group :disabled="fItem.readOnly === '0'" style="width: 80%" v-model="formData.CRFSTS">
                  <el-radio :label="item.label" v-for="item in esrfStatusOptions" :key="item.value">{{
                    item.label
                  }}</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>

            <!-- 日期 -->
            <el-form-item
              :label="`${fItem.variableName}${fItem.entry ? '(' + fItem.entry + ')' : ''}：`"
              v-else-if="fItem.variableType === '30'"
              :prop="fItem.required === '0' || fItem.regEx ? fItem.variable : ''"
            >
              <el-date-picker
                v-if="fItem.variableValue && fItem.variableValue.modifyEntryDate === 2"
                v-model="formData[fItem.variable]"
                :disabled="fItem.readOnly === '0'"
                type="date"
                clearable
                :value-format="fItem.entry"
                style="width: 80%"
                placeholder="选择日期"
              >
              </el-date-picker>
              <div v-else class="input-date">
                <el-input
                  style="width: 80%"
                  placeholder="请输入"
                  v-model="formData[fItem.variable]"
                  :disabled="fItem.readOnly === '0'"
                ></el-input>
                <el-date-picker
                  v-model="formData[fItem.variable + 'input']"
                  @change="value => handleDateTimeChange(value, fItem.variable)"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                  style="width: 30px; padding-left: 2px"
                  type="date"
                >
                </el-date-picker>
              </div>
            </el-form-item>

            <!-- 时间 -->
            <el-form-item
              :label="`${fItem.variableName}${fItem.entry ? '(' + fItem.entry + ')' : ''}：`"
              v-else-if="fItem.variableType === '40'"
              :prop="fItem.required === '0' || fItem.regEx ? fItem.variable : ''"
            >
              <el-time-picker style="width: 80%" v-model="formData[fItem.variable]" placeholder="选择时间">
              </el-time-picker>
            </el-form-item>
            <!-- 日期时间 -->
            <el-form-item
              :label="`${fItem.variableName}${fItem.entry ? '(' + fItem.entry + ')' : ''}：`"
              v-else-if="fItem.variableType === '50'"
              :prop="fItem.required === '0' || fItem.regEx ? fItem.variable : ''"
            >
              <el-date-picker
                style="width: 80%"
                v-model="formData[fItem.variable]"
                type="datetime"
                :disabled="fItem.readOnly === '0'"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>

            <!-- 数值 -->
            <el-form-item
              :label="`${fItem.variableName}${fItem.entry ? '(' + fItem.entry + ')' : ''}：`"
              v-else-if="fItem.variableType === '60'"
              :prop="fItem.required === '0' || fItem.regEx ? fItem.variable : ''"
            >
              <el-input-number
                v-model="formData[fItem.variable]"
                style="width: 80%"
                :min="1"
                :precision="fItem.variableValue.form.split('.')[1]"
                :max="numMaxType[fItem.variableValue.form.split('.')[0]]"
                :disabled="fItem.readOnly === '0'"
                clearable
              ></el-input-number>
            </el-form-item>

            <!-- 字符 -->
            <el-form-item
              :label="`${fItem.variableName}${fItem.entry ? '(' + fItem.entry + ')' : ''}：`"
              v-else-if="fItem.variableType === '70' && !specialField.includes(fItem.variable)"
              :prop="fItem.required === '0' || fItem.regEx ? fItem.variable : ''"
            >
              <el-input
                style="width: 80%"
                placeholder="请输入"
                v-model="formData[fItem.variable]"
                :disabled="fItem.readOnly === '0'"
              ></el-input>
            </el-form-item>

            <!-- 字符数值 -->
            <el-form-item
              :label="`${fItem.variableName}${fItem.entry ? '(' + fItem.entry + ')' : ''}：`"
              v-else-if="fItem.variableType === '80'"
              :prop="fItem.required === '0' || fItem.regEx ? fItem.variable : ''"
            >
              <el-select
                v-model="formData[fItem.variable + 'value1']"
                style="width: 80%"
                :disabled="fItem.readOnly === '0'"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in characterValueList" :key="item.value" :label="item.text" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <!-- 日期 -->
            <el-form-item
              :label="`${fItem.variableName}${fItem.entry ? '(' + fItem.entry + ')' : ''}：`"
              v-else-if="fItem.variableType === '90'"
              :prop="fItem.required === '0' || fItem.regEx ? fItem.variable : ''"
            >
              <el-select
                v-model="formData[fItem.variable + 'value1']"
                :disabled="fItem.readOnly === '0'"
                placeholder="年"
                style="width: 20%"
                clearable
              >
                <el-option v-for="item in yearsList" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
              &nbsp;
              <el-select
                v-model="formData[fItem.variable + 'value2']"
                :disabled="fItem.readOnly === '0'"
                placeholder="月"
                style="width: 20%"
                clearable
                v-if="fItem.variableValue.accuracy <= 2"
              >
                <el-option v-for="item in monthList" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
              &nbsp;
              <el-select
                v-model="formData[fItem.variable + 'value3']"
                :disabled="fItem.readOnly === '0'"
                placeholder="日"
                style="width: 20%"
                clearable
                v-if="fItem.variableValue.accuracy <= 1"
              >
                <el-option v-for="item in dayList" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
            </el-form-item>
            <!-- 字符时间 -->
            <el-form-item
              :label="`${fItem.variableName}${fItem.entry ? '(' + fItem.entry + ')' : ''}：`"
              v-else-if="fItem.variableType === '100'"
              :prop="fItem.required === '0' || fItem.regEx ? fItem.variable : ''"
            >
              <el-select
                v-model="formData[fItem.variable + 'value1']"
                :disabled="fItem.readOnly === '0'"
                placeholder="时"
                style="width: 20%"
                clearable
                v-if="fItem.variableValue.accuracy <= 3"
              >
                <el-option v-for="item in hoursList" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
              &nbsp;
              <el-select
                v-model="formData[fItem.variable + 'value2']"
                :disabled="fItem.readOnly === '0'"
                placeholder="分"
                style="width: 20%"
                clearable
                v-if="fItem.variableValue.accuracy <= 2"
              >
                <el-option v-for="item in minAndSecondList" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
              &nbsp;
              <el-select
                v-model="formData[fItem.variable + 'value3']"
                :disabled="fItem.readOnly === '0'"
                placeholder="秒"
                style="width: 20%"
                clearable
                v-if="fItem.variableValue.accuracy <= 1"
              >
                <el-option v-for="item in minAndSecondList" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
            </el-form-item>
            <!-- 长字符 -->
            <el-form-item
              :label="`${fItem.variableName}${fItem.entry ? '(' + fItem.entry + ')' : ''}：`"
              v-else-if="fItem.variableType === '110'"
              :prop="fItem.required === '0' || fItem.regEx ? fItem.variable : ''"
            >
              <el-input
                style="width: 80%"
                type="textarea"
                :rows="4"
                placeholder="请输入"
                v-model="formData[fItem.variable]"
                :disabled="fItem.readOnly === '0'"
              ></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="handleConfirm">确认</el-button>
        <el-button size="mini" @click="handleCancel()">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import {
  yearsList,
  monthList,
  dayList,
  characterValueList,
  hoursList,
  minAndSecondList,
} from '@/utils/enums/ecrf-design.js'

export default {
  props: {
    addVisible: {
      type: Boolean,
      default: false,
    },
    coreNameOptions: {
      type: Array,
    },
    subjectStateOptions: {
      type: Array,
    },
    // 原始的表头数据
    originTableHeadData: {
      type: Array,
    },
    projectCode: {
      type: String,
    },
  },
  data() {
    return {
      yearsList,
      monthList,
      dayList,
      characterValueList,
      minAndSecondList,
      hoursList,
      formData: {
        SITENAME: '',
        SITEID: ''
      },
      formRules: {},
      esrfStatusOptions: [
        { label: '草稿', value: '0' },
        { label: '审核中', value: '1' },
        { label: '已冻结', value: '2' },
      ],
      projectDatabaseId: '',
      projectId: '',
      databaseId: '',
      useVersion: '',
      environment: '',
      CRFVEROptionsEnums: {},
      specialField: ['SITENAME', 'STATUS', 'CRFSTS'],
      coreName: '',
    }
  },
  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.projectDatabaseId = localStorage.getItem('project-database-Id') || ''
    this.environment = localStorage.getItem('environment') || '0'
  },
  watch: {
    // 新增弹窗打开
    addVisible(newV) {
      if (newV) {
        this.originTableHeadData.map((fItem, fIndex) => {
          if (fItem.defaultValue) {
            this.formData[fItem.variable] = fItem.defaultValue
          }
          // 设置表单校验
          this.formRules[fItem.variable] = []
          if (fItem.regEx) {
            this.formRules[fItem.variable].push({
              pattern: fItem.regEx,
              message: '正则校验未通过，请检查数据!',
              trigger: 'blur',
            })
          }
          if (fItem.required === '0' && fItem.variable !== 'SITENAME') {
            this.formRules[fItem.variable].push({ required: true, message: '请输入', trigger: 'blur' })
          }

          if (fItem.variable === 'STUDYID') {
            this.formData.STUDYID = this.projectCode || ''
          }
          if (fItem.variable === 'CRFSTS') {
            this.formData.CRFSTS = '草稿'
          }
        })
        // 选中第一个中心
        if (this.coreNameOptions && this.coreNameOptions.length > 0) {
          this.handleCoreNameChange(this.coreNameOptions[0].coreId)
        }
        this.formData.STATUS = this.subjectStateOptions[0].codeValue || ''
        console.log(9999999, this.formData.STATUS)
      }
    },
  },
  methods: {
    ...mapActions('subjectInformation', ['getUpdateSubjectInfo', 'addSaveSubject']),

    // 中心名称选择
    async handleCoreNameChange(val) {
      console.log(val, 'val')
      // 中心编号
      this.formData.centreCode = this.coreNameOptions.find(item => item.coreId === val).coreCode
      const obj = this.coreNameOptions.find(item => item.coreId === val)
      console.log(obj, 'obj')

      this.coreName = obj.coreName
      this.databaseId = obj.databaseId
      this.useVersion = obj.useVersion
      this.formData.SITEID = obj.coreCode
      this.formData.SITENAME = obj.coreId
      this.formData.CRFVER = obj.versionNum ? obj.versionNum : obj.useVersion
      
    },

    // 💭点击确认
    async handleConfirm() {
      await this.$refs.formRef.validate()
      // 数据处理开始
      const data = {
        coreId: this.formData.SITENAME,
        projectId: this.projectId,
        databaseId: this.databaseId,
        useVersion: this.useVersion,
        environment: this.environment,
        values: [],
      }
      // 组织接口入参
      this.originTableHeadData.map((oItem, oIndex) => {
        const obj = {
          variable: oItem.variable,
          variableName: oItem.variableName,
          variableValue: oItem.variable === 'SITENAME' ? this.coreName : this.formData[oItem.variable],
        }
        data.values.push(obj)
      })

      if (data.values.length > 0) {
        this.handleAddSubject(data)
      } else {
        console.log('异常信息', data.values)
      }
    },

    // 新增受试者
    handleAddSubject(data) {
      this.addSaveSubject({ data }).then(res => {
        if (res.code === 200) {
          this.formData = {}
          this.$refs.formRef.resetFields()
          this.$emit('handleAddCancel', 'refresh')
        }
      })
    },

    // 取消
    handleCancel() {
      this.formData = {
        SITENAME: ''
      }
      this.$refs.formRef.resetFields()
      this.$emit('handleAddCancel')
    },

    // 允许修改时间
    handleDateTimeChange(value, field) {
      // console.log('value, field', value, field)
      // this.$set(this.formData, field, value)
      // this.$set(this.formData, field + 'input', value)
    },
  },
}
</script>

<style lang="scss" scoped>
.input-date {
  /deep/ .el-input__inner {
    padding-left: 0px;
  }
}
/deep/ .el-radio {
  line-height: 2;
}
</style>
